from django import forms

from django import template
from django.utils.translation import ugettext as _


from fbconnect.__init__ import *

if not settings.AUTH_PROFILE_MODULE:
    raise SiteProfileNotAvailable
try:
    app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
    Profile = models.get_model(app_label, model_name)
except (ImportError, ImproperlyConfigured):
    raise SiteProfileNotAvailable

if not Profile:
    raise SiteProfileNotAvailable

class FBConnectForm(forms.Form):
    # Facebook Information Stuff
    about_me = forms.CharField(required = False)
    activities = forms.CharField(required = False)
    birthday = forms.CharField(required = False)
    current_location_city = forms.CharField(required = False)
    current_location_country = forms.CharField(required = False)
    current_location_state = forms.CharField(required = False)
    current_location_zip = forms.CharField(required = False)

    first_name = forms.CharField()
    last_name = forms.CharField()

    has_added_app = forms.CharField(required = False)
    interests = forms.CharField(required = False)
    is_app_user = forms.CharField(required = False)
    locale = forms.CharField(required = False)
    movies = forms.CharField(required = False)
    music = forms.CharField(required = False)

    pic = forms.CharField(required = False)
    pic_big = forms.CharField(required = False)
    pic_small = forms.CharField(required = False)
    pic_square = forms.CharField(required = False)

    profile_update_time = forms.CharField()
    relationship_status = forms.CharField(required = False)
    religion = forms.CharField(required = False)
    sex = forms.CharField(required = False)
    status_message = forms.CharField(required = False)
    timezone = forms.CharField(required = False)


    music = forms.CharField(required = False)

    # SESSION STUFF
    session_key = forms.CharField()
    uid = forms.CharField()
    secret = forms.CharField()
    sig = forms.CharField()
    expires = forms.CharField()

    def clean_birthday(self):
        try:
            #December 22, 1985
            birthday = self.cleaned_data.get('birthday')
            try:
                new_birthday = datetime.datetime.strptime(birthday, '%B %d, %Y')
            except:
                new_birthday = datetime.datetime.strptime(birthday, '%B %d')
            return new_birthday
        except:
            None


    def clean_has_added_app(self):
        if self.cleaned_data.get('has_added_app') == 'true':
            return True
        else:
            return False


    def clean_is_app_user(self):
        if self.cleaned_data.get('is_app_user') == 'true':
            return True
        else:
            return False

    def clean_profile_update_time(self):
        try:
            return datetime.datetime.fromtimestamp(float(self.cleaned_data.get('profile_update_time')))
        except:
            raise forms.ValidationError(_('Please provide a valid profile update time'))

    def clean_expires(self):
        try:
            return datetime.datetime.fromtimestamp(float(self.cleaned_data.get('expires')))
        except:
            raise forms.ValidationError(_('Please provide a valid expire time'))


    def clean_uid(self):
        return int(self.cleaned_data.get('uid'))


    def to_user(self):
        try:
            username = u'%s_%s' % (self.cleaned_data.get('first_name'), self.cleaned_data.get('last_name'))
            password = md5.md5(str(time.time())).hexdigest()
            user = User.objects.create_user(username = username, email = '', password = password)
            profile, created = Profile.objects.get_or_create(user = user)
            #profile.update_fb_data(self.cleaned_data)
            profile.save()
            return user
        except:
            raise FBConnectError(_("We're sorry, but there's already such a user registered with us"))

class UsernameForm(forms.Form):

    create_username = forms.CharField(
        widget = forms.HiddenInput,
    )

    def __init__(self, *args, **kwargs):
        if kwargs.has_key('choices'):
            choices = kwargs.get('choices')
            del kwargs['choices']
        else:
            raise FBConnectError(_("We're sorry, but there were no username choices provided"))

        super(UsernameForm, self).__init__(*args, **kwargs)

        self.fields['system_names'] = forms.ChoiceField(
            widget = forms.RadioSelect,
            choices = choices,
            required = True
        )

        self.fields['user_choice'] = forms.CharField(
            required = False,
        )

        self.choices = choices

    def get_template(self, context = {}):
        tpl = template.loader.get_template('fbconnect/username.html')
        context.update({'form':self})
        return tpl.render(
            template.Context(
                context
            )
        )

    def clean(self):
        data = self.cleaned_data

        if data.get('system_names') == 'other':
            username = data.get('user_choice', None)
            if not username:
                raise forms.ValidationError, _("Please provide a username for your choice")
        else:
            username = data.get('system_names')

        if not username:
            raise forms.ValidationError, _('Please provide a username')

        username = username.strip()

        try:
            user = User.objects.get(username = username)
            raise forms.ValidationError, _("This username is already in use")
        except User.DoesNotExist:
            pass

        self.username = username

        return data

    def create_user(self):
        password = User.objects.make_random_password()
        user = User.objects.create_user(self.username, password = password, email = '')
        profile, created = Profile.objects.get_or_create(user = user, location = '')
        return user
